package com.aboxes.mp3.mp3player.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Queue;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;

import com.aboxes.mp3.model.Mp3Info;
import com.aboxes.mp3.mp3player.LrcProcessor;

public class PlayerService extends Service {
	private boolean isPlaying = false;
	private boolean isPause = false;
	private boolean isReleased = false;
	private MediaPlayer mediaPlayer = null;
	private ArrayList<Queue> queues = null;
	private Handler handler = new Handler();
	private UpdateTimeCallback updateTimeCallback = null;
	private long begin = 0;
	private long nextTimeMill = 0;
	private long currentTimeMill = 0;
	private String message = null;
	private long pauseTimeMills = 0;
	Queue times = null;
	Queue messages = null;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Mp3Info mp3Info = (Mp3Info) intent.getSerializableExtra("mp3Info");
		int MSG = intent.getIntExtra("MSG", 0);
		if (mp3Info != null) {
			if (MSG == AppConstant.PlayerMsg.PLAY_MSG) {
				play(mp3Info);
			}
		} else {
			if (MSG == AppConstant.PlayerMsg.PAUSE_MSG) {
				pause();
			} else if (MSG == AppConstant.PlayerMsg.STOP_MSG) {
				stop();
			}
		}

		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}

	private void play(Mp3Info mp3Info) {
		// TODO Auto-generated method stub
		if (!isPlaying) {
			String path = getMp3Path(mp3Info);
			mediaPlayer = MediaPlayer.create(this, Uri.parse("file://" + path));
			mediaPlayer.setLooping(false);
			mediaPlayer.start();
			prepareLrc(mp3Info.getLrcName());
			System.out.println("haha" + mp3Info.getLrcName());
			handler.postDelayed(updateTimeCallback, 5);
			begin = System.currentTimeMillis();
			isPlaying = true;
			isReleased = false;
		}

	}

	private void stop() {
		// TODO Auto-generated method stub

		// TODO Auto-generated method stub
		if (mediaPlayer != null) {
			if (isPlaying) {
				if (!isReleased) {
					handler.removeCallbacks(updateTimeCallback);
					mediaPlayer.stop();
					mediaPlayer.release();
					isReleased = true;
				}
				isPlaying = false;
			}
		}

	}

	public void pause() {

		if (isPlaying) {

			mediaPlayer.pause();
			handler.removeCallbacks(updateTimeCallback);
			pauseTimeMills = System.currentTimeMillis();

		} else {
			mediaPlayer.start();
			handler.postDelayed(updateTimeCallback, 5);
			begin = System.currentTimeMillis() - pauseTimeMills + begin;

		}
		isPlaying = isPlaying ? false : true;

	}

	private String getMp3Path(Mp3Info mp3Info) {
		// TODO Auto-generated method stub

		String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
		String path = SDCardRoot + File.separator + "mp3" + File.separator + mp3Info.getMp3Name();

		return path;
	}

	private void prepareLrc(String lrcName) {
		try {
			InputStream inputStream = new FileInputStream(Environment.getExternalStorageDirectory().getAbsoluteFile() + File.separator + "mp3/" + lrcName);
			LrcProcessor lrcProcessor = new LrcProcessor();
			queues = lrcProcessor.process(inputStream);
			updateTimeCallback = new UpdateTimeCallback(queues);
			begin = 0;
			currentTimeMill = 0;
			nextTimeMill = 0;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public class UpdateTimeCallback implements Runnable {
		ArrayList<Queue> queues = null;

		public UpdateTimeCallback(ArrayList<Queue> queues) {
			this.queues = queues;

		}

		@Override
		public void run() {

			times = queues.get(0);
			messages = queues.get(1);
			// TODO Auto-generated method stub
			long offset = System.currentTimeMillis() - begin;
			if (currentTimeMill == 0) {
				nextTimeMill = (Long) times.poll();
				message = (String) messages.poll();

			}
			if (offset >= nextTimeMill) {
				Intent intent = new Intent();
				intent.setAction(AppConstant.LRC_MESSAGE_ACTION);
				intent.putExtra("lrcMessage", message);
				System.out.println("----lrc:" + message);
				sendBroadcast(intent);

				message = (String) messages.poll();
				nextTimeMill = (Long) times.poll();
			}
			currentTimeMill = currentTimeMill + 10;
			handler.postDelayed(updateTimeCallback, 10);
		}
	}
}
